// store/index.js - 管理应用的全局状态 (Vue 3版本)
import { createStore } from 'vuex'

export default createStore({
  state: {
    // 任务列表数据
    tasks: [
      {
        id: 1,
        title: '英语单词学习',
        description: '',
        startTime: '09:00',
        duration: 10,
        isCompleted: false,
        isRecurring: true,
        recurrencePattern: 'weekly',
        skipHolidays: true,
        date: new Date().toISOString()
      },
      {
        id: 2,
        title: '数学练习',
        description: '',
        startTime: '14:30',
        duration: 20,
        isCompleted: false,
        isRecurring: true,
        recurrencePattern: 'workdays',
        skipHolidays: true,
        date: new Date().toISOString()
      },
      {
        id: 3,
        title: '阅读故事书',
        description: '',
        startTime: '08:00',
        duration: 15,
        isCompleted: true,
        isRecurring: true,
        recurrencePattern: 'daily',
        skipHolidays: true,
        date: new Date().toISOString()
      },
      {
        id: 4,
        title: '户外活动',
        description: '',
        startTime: '16:00',
        duration: 30,
        isCompleted: false,
        isRecurring: false,
        recurrencePattern: '',
        skipHolidays: false,
        date: new Date().toISOString()
      }
    ],
    // API Key设置
    apiKey: 'sk-1234567890abcdefghijklmnopqrstuv',
    // 每日提醒时间
    dailyReminderTime: '08:00',
    // 当前选中的日期
    selectedDate: new Date().toISOString()
  },
  mutations: {
    // 添加新任务
    addTask(state, task) {
      const newTask = {
        id: Date.now(), // 使用时间戳作为唯一ID
        ...task,
        date: state.selectedDate
      }
      state.tasks.push(newTask)
      // 保存到本地存储
      uni.setStorageSync('tasks', state.tasks)
    },
    
    // 更新任务
    updateTask(state, updatedTask) {
      const index = state.tasks.findIndex(task => task.id === updatedTask.id)
      if (index !== -1) {
        state.tasks[index] = { ...updatedTask }
        // 保存到本地存储
        uni.setStorageSync('tasks', state.tasks)
      }
    },
    
    // 删除任务
    deleteTask(state, taskId) {
      state.tasks = state.tasks.filter(task => task.id !== taskId)
      // 保存到本地存储
      uni.setStorageSync('tasks', state.tasks)
    },
    
    // 切换任务完成状态
    toggleTaskCompletion(state, taskId) {
      const task = state.tasks.find(task => task.id === taskId)
      if (task) {
        if (!task.isRecurring) {
          // 一次性任务，直接切换完成状态
          task.isCompleted = !task.isCompleted
        } else {
          // 周期性任务，需要为每天单独记录完成状态
          // 如果没有completedDates数组，创建一个
          if (!task.completedDates) {
            task.completedDates = []
          }
          
          const today = new Date().toDateString()
          // 查找今天是否已经标记为完成
          const todayIndex = task.completedDates.indexOf(today)
          
          if (todayIndex > -1) {
            // 如果今天已经完成，取消完成
            task.completedDates.splice(todayIndex, 1)
          } else {
            // 如果今天未完成，标记为完成
            task.completedDates.push(today)
          }
        }
        // 保存到本地存储
        uni.setStorageSync('tasks', state.tasks)
      }
    },
    
    // 设置选中的日期
    setSelectedDate(state, date) {
      state.selectedDate = date
    },
    
    // 设置API Key
    setApiKey(state, apiKey) {
      state.apiKey = apiKey
      // 保存到本地存储
      uni.setStorageSync('apiKey', apiKey)
    },
    
    // 设置每日提醒时间
    setDailyReminderTime(state, time) {
      state.dailyReminderTime = time
      // 保存到本地存储
      uni.setStorageSync('dailyReminderTime', time)
    },
    
    // 从本地存储加载数据
    loadFromStorage(state) {
      const savedTasks = uni.getStorageSync('tasks')
      const savedApiKey = uni.getStorageSync('apiKey')
      const savedReminderTime = uni.getStorageSync('dailyReminderTime')
      
      if (savedTasks) {
        state.tasks = savedTasks
      }
      
      if (savedApiKey) {
        state.apiKey = savedApiKey
      }
      
      if (savedReminderTime) {
        state.dailyReminderTime = savedReminderTime
      }
    }
  },
  actions: {
    // 初始化应用数据
    initApp({ commit }) {
      commit('loadFromStorage')
    }
  },
  getters: {
    // 获取选中日期的任务
    selectedDateTasks: (state) => {
      const selectedDate = new Date(state.selectedDate).toDateString()
      return state.tasks.filter(task => {
        if (!task.isRecurring) {
          // 一次性任务，直接比较日期
          const taskDate = new Date(task.date).toDateString()
          return taskDate === selectedDate
        } else {
          // 周期性任务，需要判断是否应该在选中日期显示
          const taskDate = new Date(task.date)
          const selected = new Date(state.selectedDate)
          
          // 只显示今天或未来的任务
          if (selected >= taskDate) {
            // 根据重复模式判断
            switch (task.recurrencePattern) {
              case 'daily':
                // 每天重复，任何日期都显示
                return true
              case 'weekly':
                // 每周重复，检查星期几是否相同
                return selected.getDay() === taskDate.getDay()
              case 'workdays':
                // 工作日重复，检查是否是周一到周五
                const dayOfWeek = selected.getDay()
                return dayOfWeek >= 1 && dayOfWeek <= 5
              default:
                // 其他情况，默认不显示
                return false
            }
          }
          return false
        }
      }).map(task => {
        // 为每个任务添加isCompletedToday属性，表示当天是否已完成
        if (task.isRecurring) {
          // 周期性任务，检查completedDates数组中是否包含今天
          const isCompletedToday = task.completedDates && task.completedDates.includes(selectedDate)
          return { ...task, isCompletedToday }
        } else {
          // 一次性任务，使用原有的isCompleted属性
          return { ...task, isCompletedToday: task.isCompleted }
        }
      })
    },
    
    // 获取任务统计数据
    taskStatistics: (state) => {
      const completedTasks = state.tasks.filter(task => task.isCompleted).length
      const totalTasks = state.tasks.length
      const completionRate = totalTasks > 0 ? Math.round((completedTasks / totalTasks) * 100) : 0
      
      return {
        completedTasks,
        pendingTasks: totalTasks - completedTasks,
        completionRate
      }
    },
    
    // 获取一周的任务数据（用于图表显示）
    weeklyTaskData: (state) => {
      const data = [0, 0, 0, 0, 0, 0, 0] // 一周7天的数据
      const today = new Date()
      
      // 计算本周一的日期
      const firstDayOfWeek = new Date(today)
      firstDayOfWeek.setDate(today.getDate() - today.getDay() + 1) // 周一
      
      state.tasks.forEach(task => {
        const taskDate = new Date(task.date)
        const dayDiff = Math.floor((taskDate - firstDayOfWeek) / (1000 * 60 * 60 * 24))
        
        // 如果任务在本周内
        if (dayDiff >= 0 && dayDiff < 7) {
          data[dayDiff]++
        }
      })
      
      return data
    }
  }
})